package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.*;

class BinaryTreeZigzagLevelOrderTraversal{
    // 2023-05-01 02:18:18
    public static void main(String[] args) {
        Solution solution = new BinaryTreeZigzagLevelOrderTraversal().new Solution();
    }
    
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root==null)return ans;

        Queue<TreeNode> queue=  new LinkedList();
        queue.offer(root);
        int level = 1;
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer>  levelValueList = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node!=null){
                    levelValueList.add(node.val);
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
            if (!levelValueList.isEmpty()){
                if (level%2==0){
                    Collections.reverse(levelValueList);
                    ans.add(levelValueList);
                }else {
                    ans.add(levelValueList);
                }
            }
            level++;
        }
        return ans;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}